package com.kyzh.core.pager.me

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.atools.util.setHeight
import com.gushenge.atools.util.setWidth
import com.gushenge.core.base.Base
import com.gushenge.core.beans.Nav
import com.gushenge.core.beans.UserCenter
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.requests.UserRequest
import com.gushenge.core.toast
import com.kyzh.core.R
import com.kyzh.core.activities.*
import com.kyzh.core.pager.me.settings.SettingsV3Activity
import com.kyzh.core.pager.weal.sign.SignActivity
import com.kyzh.core.pager.weal.vip.VipCentreActivity
import com.kyzh.core.databinding.FragMeV31Binding
import com.kyzh.core.databinding.FragMeV3TopDetailBinding
import com.gushenge.core.base.fragment.BaseFragment
import com.kyzh.core.adapters.NavAdapter
import com.kyzh.core.utils.*
import com.kyzh.core.pager.login.LoginActivity
import com.kyzh.core.pager.me.user.UserDataActivity
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMUserFullInfo
import kotlinx.android.synthetic.main.frag_me_v3_2.*
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.support.v4.startActivity


class MeFragment1 : BaseFragment() {


    private lateinit var binding : FragMeV31Binding
    private var huiyuan_url = ""
    private var vip = 0
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_me_v3_1, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        initData()
        initView()
    }
    fun initView(){
        binding?.tvOpen.setOnClickListener {
            if (startLogin()) {
                if(vip == 0) {
                    if (huiyuan_url.isNullOrEmpty()) {
                        "未配置链接".toast()
                        return@setOnClickListener
                    }
                    startActivity<BrowserActivity>(
                        GlobalKeys.TITLE to "",
                        GlobalKeys.LINK to huiyuan_url
                    )
                }
            }
        }
        binding?.ivNoVip.setOnClickListener {
            if (startLogin()) {
                if(vip == 0){
                    if(huiyuan_url.isNullOrEmpty()){
                        "未配置链接".toast()
                        return@setOnClickListener
                    }
                    startActivity<BrowserActivity>(
                        GlobalKeys.TITLE to "",
                        GlobalKeys.LINK to huiyuan_url
                    )
                }

            }
        }
    }

    var mCustomInfo: HashMap<String,ByteArray> = hashMapOf()
    fun initData() {

        UserRequest.newUserCenter {
            if (this == null) {
                startActivity<LoginActivity>()
            } else {
                val data = this
                huiyuan_url = this.config.huiyuan_url
                vip = this.user.vip
                val v2TIMUserFullInfo = V2TIMUserFullInfo()
                v2TIMUserFullInfo.setNickname(user.user_name)
                v2TIMUserFullInfo.faceUrl = user.face
                //  val color: ArrayList<String> = arrayListOf(),  //颜色
                //            val head_frame: String= "",  //头像框
                //            val medal: String= "",  //勋章
                //            val vip: Int = 0,  //当前VIP等级，如果是0显示未开通
                // 设置自定义字段   后期加入头像框等参数
                mCustomInfo.clear()
                var color = ""
                kotlin.runCatching {
                    //因为是集合 所以转换处理下  避免崩溃  错误就不放color了
                    user.color.forEach {
                        color = if (!color.isNullOrEmpty()) {
                            //内容较少不考虑性能了 就这样拼接
                            "$color,$it"
                        } else {
                            it
                        }
                    }
                }.onSuccess {
                    mCustomInfo["color"] = color.toByteArray()
                    mCustomInfo["medal"] = user.medal.toByteArray()
                    mCustomInfo["headf"] = user.head_frame.toByteArray()
                    mCustomInfo["vip"] = user.vip.toString().toByteArray()
                    mCustomInfo["vipimg"] = user.vip_img.toByteArray()

                }.onFailure {
                    mCustomInfo["medal"] = user.medal.toByteArray()
                    mCustomInfo["headf"] = user.head_frame.toByteArray()
                    mCustomInfo["vip"] = user.vip.toString().toByteArray()
                    mCustomInfo["vipimg"] = user.vip_img.toByteArray()
                }
                v2TIMUserFullInfo.customInfo.putAll(mCustomInfo)
                v2TIMUserFullInfo.userID
                //设置用户资料
                V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo,object : V2TIMCallback {
                    override fun onSuccess() {
                        Log.e("User", "onSuccess: 用户信息设置成功 ", )
                    }

                    override fun onError(p0: Int, p1: String?) {
                        Log.e("User", "onSuccess: 用户信息设置失败  $p0   $p1", )
                    }

                })
                binding.config = config
                binding.data = user
                binding.apply {
                    if(!checkLogin()){
                        tvSign.setVisibility(false)
                    }else{
                        tvSign.setVisibility(true)
                    }
                    if(data.user.is_qiandao == 0){
                        tvSign.text = "签到"
                        tvSign.setOnClickListener {
                            if (startLogin()) {
                                startActivity<SignActivity>()
                            }
                        }
                        tvSign.setTextColor(Color.parseColor("#444444"))
                        tvSign.backgroundResource = R.drawable.bg_sign
                        tvSign.isEnabled = true
                    }else{
                        tvSign.text = "已签到"
                        tvSign.isEnabled = false
                        tvSign.setTextColor(Color.parseColor("#EEC46F"))
                        tvSign.backgroundResource = R.drawable.bg_signed
                    }
                    if(data.user.vip == 0){
                        group1.setVisibility(false)
                        tvOpen.setVisibility(true)
                        xunzhang.setVisibility(false)
                        tips.setVisibility(false)

                    }else{
                        //会员
                        group1.setVisibility(true)
                        tvOpen.setVisibility(false)
                        xunzhang.setVisibility(true)
                        tips.setVisibility(true)
                        kotlin.runCatching {
                            tvExp.text = "当前VIP值：${data.config.exp}，距离下一级剩余:${data.config.last_exp.toInt()-data.config.exp.toInt()}"
                            progress.progress = data.config.exp.toInt()*100/data.config.last_exp.toInt()
                        }

                        tvExp1.text = "当前${data.config.vip}"
                        tvExp2.text = data.config.last_vip
                    }
                    if(data.user.head_frame.isNullOrEmpty()){
//                        ivBg.setVisibility(false)
                        header.setHeight(dip(62))
                        header.setWidth(dip(62))
                    }else{
                        header.setHeight(dip(62))
                        header.setWidth(dip(62))
                        ivBg.setVisibility(true)
                    }
                    tv1.setOnClickListener {
                        VipCentreActivity.start(requireActivity())
                    }
                    info1.setInfo("卡券", data.user.coupon)
                    info1.root.setOnClickListener {
                        startActivity<MyCouponActivity>()
                    }
                    info2.setInfo(getString(R.string.pointText), data.user.point)
                    info2.root.setOnClickListener {
                        startActivity<PointsMallActivity>()
                    }
                    info3.setInfo(getString(R.string.yuyue), data.user.yuyue)
                    info4.setInfo(getString(R.string.ptb), data.user.coin)
                    info4.root.setOnClickListener {
                        if (startLogin()) {
                            startActivity<BrowserActivity>(
                                GlobalKeys.TITLE to getString(R.string.ptbRecharge),
                                GlobalKeys.LINK to "${Base.BASEURLV3}/?ct=coin&uid=${MMKVConsts.uid}&t=$time&sign=${
                                    httpSign(MMKVConsts.uid)
                                }"
                            )
                        }
                    }
                    ivMessage.setOnClickListener {
                        if (startLogin()) {
                            startActivity<NoticeActivity>()
                        }
                    }

                    ivSetting.setOnClickListener {
                        startActivity<SettingsV3Activity>()
                    }

                    header.setOnClickListener {
                        if (startLogin()){
                            startActivity<UserDataActivity>()
                        }
                    }
                    userShow.setOnClickListener {
                        if (startLogin()){
                            startActivity<UserDataActivity>()
                        }
                    }

                    if(data.user.color.isNullOrEmpty()){
                        tvName .setHasColors(false,null)
                        tvName.setText(data.user.user_name)
                    }else{
                        if(data.user.color.size == 1){
                            tvName.setText(data.user.user_name)
                            tvName .setHasColors(false,null)
                            tvName.setTextColor(Color.parseColor(data.user.color[0]))
                        }else{
                            var intArray = IntArray(data.user.color!!.size)
                            data.user.color?.forEachIndexed { index, s ->
                                intArray[index] = Color.parseColor(s)
                            }
                            tvName.setTextColor(Color.parseColor(data.user.color[0]))
                            tvName.setText(data.user.user_name)
                            tvName .setHasColors(true,intArray)

//                            tvName .setSlide(true)
                        }
                    }


                    initMeFun(data.nav)
                    initQuanzi(data.quanzi.lists)
                }
            }
            UserRequest.hasNewMessage {
                binding.ivHasNotice.visibility = if (this) View.VISIBLE else View.GONE
            }
        }
    }
    private fun FragMeV31Binding.initQuanzi(list: ArrayList<UserCenter.QuanziList>) {
        if (list.isEmpty()){
            lingame.visibility = View.GONE
        }
        revGame.layoutManager = object : GridLayoutManager(requireContext(), 4){
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        revGame.adapter = QuanziAdapter(R.layout.item_frag_me_quanzi, list)
    }

    private fun FragMeV31Binding.initMeFun(nav: ArrayList<Nav>) {

        revNav.layoutManager = object : GridLayoutManager(requireContext(), 4){
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        revNav.adapter = NavAdapter(R.layout.item_frag_me_function, nav)
    }
    private inner class QuanziAdapter(layout: Int, beans: ArrayList<UserCenter.QuanziList>): BaseQuickAdapter<UserCenter.QuanziList, BaseViewHolder>(layout, beans) {
        override fun convert(helper: BaseViewHolder, item: UserCenter.QuanziList) {
            helper.setText(R.id.tvTitle, item.name)
            Glide.with(context).load(item.icon).into(helper.getView(R.id.ivIcon))

            helper.itemView.setOnClickListener {
                context.startGameDetailActivity(item.id)
            }
        }
    }
    private fun FragMeV3TopDetailBinding.setInfo(title1: String, info1: String){
        this.title = title1
        this.info = info1
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        initData()
    }
}